package com.example.dump.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.example.dump.bean.DataBaseInfo;
import com.example.dump.constant.DumpClient;
import com.example.dump.service.DumpDataBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;

@Slf4j
@Service
public class MysqlDumpDataBaseServiceImpl implements DumpDataBaseService {

    @Override
    public void dump(DataBaseInfo dataBaseInfo, String backFile) throws IOException, InterruptedException {

        // 执行命令
        Process process = Runtime.getRuntime().exec(toDumpCmdString(dataBaseInfo));

        // 获取命令输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        StringBuilder output = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }
        backFile = StrUtil.isNotEmpty(backFile) ? backFile : DumpClient.MYSQL_DEFAULT_BACK_PATH + File.separatorChar
                + (CollUtil.isNotEmpty(dataBaseInfo.getDatabaseNames()) ?StrUtil.join("-",dataBaseInfo.getDatabaseNames()):"all")
                +System.currentTimeMillis()+".sql";
        // 将输出写入文件
        FileWriter writer = new FileWriter(backFile);
        writer.write(output.toString());
        writer.close();

        // 等待命令执行完成
        int exitCode = process.waitFor();
        log.info("dump Command executed with exit code: {}",exitCode);
    }

    private String toDumpCmdString(DataBaseInfo dataBaseInfo) {
        ArrayList<String> cmds = CollectionUtil.newArrayList(DumpClient.MYSQl_CLIENT_NAME,
                "-h", dataBaseInfo.getIp(),
                "-P"+ dataBaseInfo.getPort(),
                "-u"+ dataBaseInfo.getUserName(),
                "-p"+ dataBaseInfo.getPassword());

        if (CollUtil.isNotEmpty(dataBaseInfo.getDatabaseNames())){
            cmds.add("--databases");
            cmds.addAll(dataBaseInfo.getDatabaseNames());
        }else {
            cmds.add("--all-databases");
        }

        return StrUtil.join(" ", cmds);
    }
}
